const http = require("http");
const fs = require("fs");
const path = require("path")
const cheerio = require('cheerio');
const https = require('https');
const querystring = require("querystring")

const app_root="www";
let Console={
    data:{
        success:"\x1B[32m",
        error:"\x1B[31m",
        log:"\x1B[37m"
    },
    error(txt){
        const str=`${Console.data.error} ${txt}\x1b[0m`;
        console.log(str);
    },
    log(txt){
        const str=`${Console.data.log} ${txt}\x1b[0m`;
        console.log(str);
    },
    success(txt){
        const str=`${Console.data.success} ${txt}\x1b[0m`;
        console.log(str);
    },
}
let path_fn=(url)=>{
    return path.resolve(app_root + url.split("?")[0]);
}
let serve=http.createServer(function(req,res){
    if(req.method==="GET"){
        if(req.url==="/"){
            res.writeHead(302,{'Location':"http://localhost:8888/index.html"}),
            res.end();
        }else{
            Get(req,res);    
        }
    }else{
        let postData='';
        req.on('data',(chunk)=>{
            postData+=chunk;
        })
        req.on("end",()=>{
            postData=querystring.parse(postData)
            router(req,res,postData);
        })
        
    }
    

}).listen(8888);
Console.success("http://localhost:8888");
/**
 * 处理get请求
 * @param {*} req 
 * @param {*} res 
 */
function Get(req,res){
    fs.readFile(path_fn(req.url),function(err,data){
        if(err){
            //res.writeHead(400,{"Content-Type":"text/html"});
            res.statusCode=404;
            res.write("页面不存在");
            Console.error(`get url:${req.url} state:400`);
        }else{
            //res.writeHead(200,{"Content-Type":"text/html"});
            res.statusCode=200;
            res.write(data.toString());
            Console.success(`get url:${req.url} state:200`);    
        }
        res.end();
    })
}
/**
 * 路由跳转函数，主要是post的请求
 * @param {*} req 
 * @param {*} res 
 * @param {*} body 
 */
function router(req,res,body){
    let config={
        base(){
            get_html(unescape(body.url),res);
        },
        address(){
            get_address(req,res,body);
        }
    };
    config[req.url.slice(1)]();
}
/**
 * 解析地址
 * @param {*} req 
 * @param {*} res 
 * @param {*} body 
 */
function get_address(req,res,body){
    http.get(formatUrl('成都市',body.address),(res)=>{
        const {statusCode}=res;
        if(statusCode!=200){
            Console.error("请求错误");
            res.resume();
            return;
        }
        res.setEncoding('utf8');
        let rawData = '';
        res.on('data', (chunk) => { rawData += chunk; });
        res.on('end', () => {
            try {
                rawData=rawData.replace('callback&&callback(',"").replace(/\)$/,"");
                const parsedData = JSON.parse(rawData);
                console.log(parsedData);
            } catch (e) {
                console.error(e.message);
            }
        });
    });
    res.end();
}
/**
 * 格式化查询数据
 * @param {*} wd 
 * @param {*} cn 
 */
function formatUrl(cs,address){
    let config={
        name:"http://api.map.baidu.com/geocoder/v2/",
        query:{
            output:"json",
            address:cs+address,
            callback:"callback",
            ak:"OCKmGWMADgUpHt6AcBRIBRHVHSS1FkEa"
        }
    };
    let url=config.name+'?';
    Object.keys(config.query).map(n=>{
        url+=n+"="+config.query[n]+"&&";
    })
    return url.slice(0,-2);
}
/**
 * 获取页面html中的数据
 * @param {*} url 
 * @param {*} response 
 */
function get_html(url,response){
    https.get(url,(res)=>{
        if(res.statusCode===200){
            let page='';
            res.on('data',(chunk)=>{
                page+=chunk;
            });
            res.on("end",()=>{
                res.setEncoding("UTF-8");
                const $=cheerio.load(page);
                let box_list=$("#list-content .zu-itemmod");
                let page_list=[],page_arr=[];
                box_list.map(function(n,el){
                    let add=$(el).find(".details-item").eq(1).find("*").remove();
                    add=$(el).find(".details-item").eq(1).text().replace(/\s|-/g,'');
                    page_list.push({
                        link:$(el).attr("link"),
                        address:add,
                        img:$(el).find(".thumbnail").attr("src"),
                        price:$(el).find(".zu-side").text().replace(/\s|-/g,''),
                    })
                });
                $(".multi-page a").map((n,el)=>{
                    if($(el).attr("class"))return;
                    page_arr.push({
                        link:$(el).attr("href"),
                        text:$(el).text()
                    });
                })
                response.writeHeader(200, {'Content-Type' : 'application/json;charset:utf-8'});
                response.write(JSON.stringify(
                    {
                        code:200,
                        data:{
                            address:page_list,
                            page:page_arr,
                        }
                    }
                ));
                response.end();
            })
        }
    })
}
